import 'dart:async';
import 'dart:convert';

import 'package:get/get.dart';
import 'package:get/get_connect/http/src/request/request.dart';
import 'package:kkhousekeep/page/login/login.dart';
import 'package:kkhousekeep/tools/toast_util.dart';
import 'package:logger_util/logger_util.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../tools/shared_preferences.dart';

class BaseConnect extends GetConnect {
  @override
  void onInit() {
    super.onInit();
    httpClient.addRequestModifier(requestInterceptor);
    httpClient.addResponseModifier(responseInterceptor);
  }

  FutureOr<Request> requestInterceptor<T>(Request<T?> request) async {
    var sp = await SharedPreferences.getInstance();
    var token = sp.getString(SpKey.accessToken);
    request.headers['Authorization'] = token ?? "";
    logI(
        'request: method -->${request.method} url-->${request.url.path}  contentLength-->${request.contentLength}'
        '  headers -->${jsonEncode(request.headers)}');
    return request;
  }

  FutureOr responseInterceptor<T>(
      Request<T?> originalRequest, Response<T?> response) async {
    logD(
        'Response : StateCode-->${response.statusCode}  body-->${jsonEncode(jsonDecode(response.bodyString ?? ""))}');
    if (isAccessTokenExpired(response)) {
      httpClient.close();
      logI("AccessToken已过期");
      ToastUtils.showToast(tip: "身份过期,请重新登陆");
      var phone = await getSp().getPhone();
      await getSp().clear();
      await getSp().setPhone(phone);
      Get.offAll(() => const LoginPage());
      return response;
    }
    return Future.value(response);
  }

  bool isAccessTokenExpired(Response response) {
    return response.statusCode == 401;
  }

  @override
  void onClose() {
    httpClient.removeRequestModifier(requestInterceptor);
    httpClient.removeResponseModifier(responseInterceptor);
    super.onClose();
  }
}
